# coding=utf-8
__author__ = 'liubin'

from tornado.web import asynchronous
from sqlalchemy import or_, desc, and_
from sqlalchemy.orm import joinedload
from tornado_json.requesthandlers import APIHandler
from project.tools import HandlerMixin, unblock, to_json
from project.models import Role, MenuRole
from base import BaseHandler
from project.forms import RoleForm;

class RoleHandler(BaseHandler):
    """
    权限API
    """
    __url_names__ = []

    #@asynchronous
    def check_code_not_exist(self, code):
        """
        检查权限编码存在
        """
        role = self.db_conn.query(Role).filter_by(code=code, isDeleted=False).first()
        if role:
            self.error(u'指定权限编号已被使用')
            return False
        return True

    #@asynchronous
    def check_id_exist(self, id):
        """
        检查ID存在
        """
        role = self.db_conn.query(Role).filter_by(id=id, isDeleted=False).first()
        if not role:
            self.error(u'指定编号不存在')
        return role


class SingleHandler(RoleHandler):
    """
    单记录
    """
    __urls__ = [r"/api/role/(?P<id>[a-zA-Z0-9_]+)/?"]

    @unblock
    def get(self, id):
        """
        获取单条记录
        """
        role = self.db_conn.query(Role).options(joinedload(Role.menus)).filter_by(id=id, isDeleted=False).first()
        #print(type(role.menus))
        self.success(to_json(role))

    @unblock
    def put(self, id):
        """
        更新单条记录
        """
        #print(self.json_args)
        role = self.check_id_exist(id)
        if role:
            data = self.json_args
            print(data)
            form = RoleForm(data=data)
            print(form)
            if form.validate():
                role.name = data.get('name')
                self.db_conn.commit()
                self.success(None)
            else:
                print(form.errors)
                messages = []
                for error in form.errors:
                    label = form.__getitem__(error).label.text
                    for msg in form.errors[error]:
                        messages.append(label + ':' + msg)
                self.error('<br/>'.join(messages))
    @unblock
    def delete(self, id):
        """
        删除单条记录
        """
        role = self.check_id_exist(id)
        if role:
            if role.code == 'ADMIN':
                self.error(u'你不能删除admin')
            else:
                role.isDeleted = True
                self.db_conn.commit()
                self.success(None)

class MenuRoleHandler(RoleHandler):
    """
    菜单权限设置
    """
    __urls__ = [r'/api/role/(?P<id>[a-zA-Z0-9_]+)/menuRole/?']

    def post(self, id):
        """
        更新菜单权限
        """
        # 使用subquery来删除
        sq = self.db_conn.query(Role.id).filter_by(id=id, isDeleted=False).subquery()
        menus = self.db_conn.query(MenuRole).filter(
            MenuRole.roleId.in_(sq)
        ).delete(synchronize_session='fetch')
        #menus.delete(synchronize_session='fetch')
        print(self.json_args)
        if self.json_args:
            user = self.get_user()
            for mr in self.json_args:
                mr['roleId'] = id
                menuRole = MenuRole(mr)
                if user:
                    menuRole.set_insert_user(user.id)
                self.db_conn.add(menuRole)
                self.db_conn.commit()
        self.success(None)



class ListHandler(RoleHandler):
    """
    记录列表
    """
    __urls__ = [r'/api/role/?']

    @unblock
    def get(self):
        """
        获取记录列表
        :return:
        """
        # 无关字段, 原样返回
        draw = self.get_query_argument('draw', 0)
        # 分页大小
        size = int(self.get_query_argument('size', 0))
        # 第几项开始
        start = int(self.get_query_argument('start', 0))
        # 查询字段
        query = self.get_query_argument('query', '')
        # 排序字段
        order = self.get_query_argument('order', '')
        # 正序或倒叙
        sort = self.get_query_argument('dir', '')
        end = start + size
        roles = self.db_conn.query(Role).filter_by(isDeleted=False)
        if query:
            roles = roles.filter(
                or_(
                    Role.code.like('%' + query + '%'),
                    Role.name.like('%' + query + '%')
                )
            )
        if order:
            if sort == 'desc':
                roles = roles.order_by(desc(getattr(Role, order)))
            else:
                roles = roles.order_by(getattr(Role, order))
        # 总件数
        total = roles.count()
        if end:
            # 分页处理
            roles = roles.slice(start, end)
        # 获取list对象
        roles = roles.all()
        # 返回值
        self.success(to_json(roles), draw=draw, total=total)

    @unblock
    def post(self):
        """
        新增
        :return:
        """
        role = Role(self.json_args)
        form = RoleForm(obj=role)
        if form.validate():
            if self.check_code_not_exist(role.code):
                #role.insertUser = self.get_current_user()
                #role.updateUser = role.insertUser
                user = self.get_user()
                if user:
                    role.set_insert_user(user.id)
                self.db_conn.add(role)
                self.db_conn.commit()
                self.success(None)
        else:
            self.error('<br/>'.join(form.errors))